package com.bluefox.hospital.convertor;

import com.bluefox.common.web.dto.AbstractConvertor;
import com.bluefox.hospital.dto.DoctorDTO;
import com.bluefox.hospital.model.Department;
import com.bluefox.hospital.model.Doctor;
import com.bluefox.hospital.service.DepartmentService;
import com.bluefox.hospital.service.DoctorService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * DoctorConvertor
 */
@Component
public class DoctorConvertor extends AbstractConvertor<Doctor, DoctorDTO> {

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DepartmentService departmentService;


    @Override
    public Doctor toModel(@NonNull final DoctorDTO dto) {
        if (dto.isNew()) {//新增
            return constructModel(dto);
        } else {//更新
            return updateModel(dto);
        }
    }

    @Override
    public DoctorDTO toDTO(@NonNull final Doctor model, final boolean forListView) {
        final DoctorDTO dto = new DoctorDTO();

        dto.setId(model.getId());
        dto.setDepartmentName(model.getDepartmentName());
        dto.setName(model.getName());
        dto.setPhoto(model.getPhoto());
        dto.setResearch(model.getResearch());
        dto.setIntroduce(model.getIntroduce());
        dto.setTitle(model.getTitle());
        dto.setDepartmentId(model.getDepartment().getId());
        dto.setIsFamousExpert(model.getIsFamousExpert());
        return dto;
    }

    /**
     * 构建新Model
     *
     * @param dto
     * @return
     */
    private Doctor constructModel(final DoctorDTO dto) {
        Doctor model = new Doctor();
        return getDoctor(dto, model);
    }

    // 更新Model
    private Doctor updateModel(final DoctorDTO dto) {
        Doctor model = doctorService.get(dto.getId());
        return getDoctor(dto, model);
    }

    private Doctor getDoctor(DoctorDTO dto, Doctor model) {
        Department department = departmentService.get(dto.getDepartmentId());
        model.setDepartment(department);
        model.setPhoto(dto.getPhoto());
        model.setDepartmentName(department.getName());
        model.setName(dto.getName());
        model.setResearch(dto.getResearch());
        model.setIntroduce(dto.getIntroduce());
        model.setTitle(dto.getTitle());
        model.setIsFamousExpert(dto.getIsFamousExpert());
        return model;
    }

}
